const express = require('express')

const router = express.Router()

let booklist = [{id:1,name:'三国',author:'罗贯中',des:'三国时期英雄豪杰们的故事'}]
let book = {}; //  单个book 数据


router.get('/books',(req,res)=>{
    res.send({
        status:200,
        msg:'success',
        booklist
    })
})

//添加书籍
router.post('/addbooks',(req,res)=>{
    let id = booklist[booklist.length -1].id + 1
    console.log(id)
    let postData = {
        id,
        ...req.body
    }
    booklist.push(postData);
    res.send({
        status:200,
        msg:'添加成功',
        booklist
    })
})

router.delete('/delbooks/:id',(req,res)=>{
    let id = req.params.id
    booklist = booklist.filter(val=>val.id!=id)
    console.log(booklist)
    res.send({
        status:200,
        msg:'删除成功',
        booklist
    })
})

router.get('/book/:id',(req,res)=>{
    let id = req.params.id;
    [book] = booklist.filter(val=>val.id == id)
    console.log(book)
    res.send(book)
})

router.put('/updatebook',(req,res)=>{
    let data = req.body;
    let id = book.id;
    let newBook = {
        id,
        ...data
    }

    booklist = booklist.map(val=> id == val.id? val = newBook : val)
    res.send({
        status:200,
        msg:'更新成功',
        booklist
    })
})


module.exports = router